package com.sunrise.xcrm.ui.list.pagingcomponent;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.sunrise.xcrm.data.Person;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;

/**
 * The container for the table support for paging and add 2 more properties: The checkbox column and the Edit/Delete
 * column.
 * 
 * @author Phan Hong Phuc
 * @since Aug 11, 2012
 * @param <T>
 */
public class ExplicitPagingContainer<T> extends AbstractRowContainer {
    public static final int PAGE_SIZE = 40;

    List<BeanItem<T>> currentPage = new ArrayList<BeanItem<T>>();

    public ExplicitPagingContainer() {
        addContainerProperty("id", Integer.class, null);
        addContainerProperty("accountName", String.class, null);
        addContainerProperty("officePhone", String.class, null);
        addContainerProperty("area", String.class, null);
        addContainerProperty("createdDate", Date.class, null);
        addContainerProperty("assignedTo", String.class, null);
        setNumberOfRows(0);
    }

    @Override
    public Item getItem(Object itemId) {
        return currentPage.get((Integer) itemId);
    }

    public void loadPage(int pageNumber) {
        // Simulate a DB call here; we'll just sleep for half a second, which is a reasonable time for a db query to
        // last
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // No-op
        }

        currentPage.clear();
        rowIds.clear();
        int numberOfRowsToGenerate = PAGE_SIZE;

        List<BeanItem<T>> items = new ArrayList<BeanItem<T>>(numberOfRowsToGenerate);
        for (int i = 0; i < PAGE_SIZE; i++) {
            int overallRowId = 1 + ((pageNumber - 1) * PAGE_SIZE) + i;
            Person person = new Person();
            person.setId(overallRowId);
            person.setAccountName("accountName");
            person.setArea("area");
            person.setAssignedTo("hungTD");
            person.setCreatedDate(new Date(2012, 12, 12));
            person.setOfficePhone("0123456789");

            items.add(new BeanItem(person));

            // TODO
            rowIds.add(i);

        }
        currentPage.addAll(items);
        setNumberOfRows(numberOfRowsToGenerate);
    }
}
